<?php

/**
 * basic file class
 *
 * @author ecv
 */
class File {

    public $file;
    public $source;

    public function __construct($options = array())
    {
        if (!empty($options['file']))
        {
            $this->file = $options['root'] . DS . $options['folder'] . DS . $options['file'];
            if (file_exists($this->file)) {
                $this->load_file();
            } else {
                $this->load_file($options['root'] . DS . $options['folder'] . DS . DEFAULT_INDEX);
            }
        }
        return;
    }

    public function load_file($file = NULL)
    {
        if ($file == NULL && isset($this->source) && !empty($this->source))
        {

            return TRUE;
        }
        if ($file != NULL)
        {
            $this->file = $file;
        }
        if (isset($this->file) && !empty($this->file))
        {
            $this->file = filter_var(
                $this->file, FILTER_VALIDATE_REGEXP,
                array(
                'options' => array(
                    'regexp' => '/^[a-zA-Z0-9\\\.\/_\-]+$/'
                )
                )
            );

            $this->file = preg_replace('/\\|\//', DS, $this->file);

            if (!empty($this->file) && is_readable($this->file))
            {
                $this->source = implode('', file($this->file));

                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

    public function __toString()
    {
        if (isset($this->output) && !empty($this->output))
        {
            return (string) $this->output;
        }
        else
        { // noting found, output raw file
            return (string) $this->source;
        }
    }

}
